package com.cloudjan.springcloud.controller;

import com.cloudjan.springcloud.entities.CommonResult;
import com.cloudjan.springcloud.entities.Payment;
import com.cloudjan.springcloud.lb.Loadbalance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * ribbon是基于客户端的负载均衡接口调用工具
 * 相当于负载均衡+RestTemplate
 */
@RestController
@Slf4j
public class OrderController {
    @Resource(name = "restTemplate")
    private RestTemplate restTemplate;

    @Resource(name = "myRestTemplate")
    private RestTemplate myRestTemplate;

    //public static final String PAYMENT_URL = "http://localhost:8001";
    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private DiscoveryClient discoveryClient;

    @Autowired
    private Loadbalance loadbalance;

    @GetMapping("/comsumer/payment/create")
    public CommonResult<Payment> create(Payment payment){
        return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class);
    }

    @GetMapping("/comsumer/payment/get/{id}")
    public CommonResult<Payment> getPaymentByid(@PathVariable("id") Long id){
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
    }

    @GetMapping("/comsumer/payment/getentity/{id}")
    public CommonResult<Payment> getPaymentEntityByid(@PathVariable("id") Long id){
        ResponseEntity<CommonResult> result = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
        log.info(result.getStatusCode().toString());
        if(result.getStatusCode().is2xxSuccessful()){
            return result.getBody();
        }else {
            return new CommonResult<>(444, "fail！");
        }
    }

    @GetMapping("/comsumer/payment/lb")
    public String testLB(){
        List<ServiceInstance> instances =  discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        if (instances == null || instances.size() <= 0) {
            return null;
        }
        ServiceInstance serviceInstance =loadbalance.instances(instances);
        URI uri = serviceInstance.getUri();
        int port = serviceInstance.getPort();
        System.out.println(uri.toString());
        //注意此处的restTemplate必须为没有带负载均衡注解的
        return myRestTemplate.getForObject(uri + "/payment/lb", String.class);
    }
}
